package com.woniu.adapter;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.outlet.dao.WorkingProcedureTypePoMapper;
import com.woniu.outlet.po.WorkingProcedureTypePo;
import com.woniu.outlet.rabbitmq.MessageRepo;
import com.woniu.outlet.redis.RedisRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class WorkingProcedureTypeAdapter {

    @Autowired
    private WorkingProcedureTypePoMapper workingProcedureTypePoMapper;

    @Autowired
    private RedisRepo redisRepo;

    @Autowired
    private MessageRepo messageRepo;


    public List<WorkingProcedureTypePo> findWorkingProcedureTypes() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String str = redisRepo.findRedisRepo("workingProcedureType:list");
        List<WorkingProcedureTypePo> lists = new ArrayList<>();
        if (!StringUtils.isEmpty(str)) {
            lists = mapper.readValue(str, new TypeReference<List<WorkingProcedureTypePo>>() {
            });
            return lists;
        }
        lists = workingProcedureTypePoMapper.selectByExample(null);
        //存到redis
        redisRepo.saveRedisRepo("workingProcedureType:list",mapper.writeValueAsString(lists));
        return lists;
    }

    public WorkingProcedureTypePo getWorkingProcedureTypeById(Long id) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String str = redisRepo.findRedisRepo("workingProcedureType:" + id);
        WorkingProcedureTypePo workingProcedureTypePo = null;
        if (!StringUtils.isEmpty(str)) {
            workingProcedureTypePo = mapper.readValue(str, new TypeReference<WorkingProcedureTypePo>() {
            });
            return workingProcedureTypePo;
        }
        workingProcedureTypePo = workingProcedureTypePoMapper.selectByPrimaryKey(id);
        //存到redis
        redisRepo.saveRedisRepo("workingProcedureType:"+id,mapper.writeValueAsString(workingProcedureTypePo));
        return workingProcedureTypePo;
    }

    public void addWorkingProcedureType(WorkingProcedureTypePo workingProcedureTypePo){
        workingProcedureTypePoMapper.insert(workingProcedureTypePo);
        redisRepo.deleteRedisRepo("workingProcedureType:list");

    }

    public void updateWorkingProcedureType(WorkingProcedureTypePo workingProcedureTypePo){
        workingProcedureTypePoMapper.updateByPrimaryKeySelective(workingProcedureTypePo);
        redisRepo.deleteRedisRepo("workingProcedureType:list");
    }

    public void deleteWorkingProcedureTypeById(Long id){
        workingProcedureTypePoMapper.deleteByPrimaryKey(id);
        redisRepo.deleteRedisRepo("workingProcedureType:list");
    }
}
